package com.comprental.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Set;


/**
 * @author yaphyao
 * @version 2017/10/13
 * @see com.fenqile.pop.api.demo
 */
public class PopHttpClientUtil {
    private final static Logger logger = LoggerFactory.getLogger(PopHttpClientUtil.class);
    private static CloseableHttpClient httpClient = null;
    private static PoolingHttpClientConnectionManager poolConnectionManager = null;

    static {
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", new PlainConnectionSocketFactory())
                .build();
        poolConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        poolConnectionManager.setMaxTotal(50);
        poolConnectionManager.setDefaultMaxPerRoute(10);
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5000).setConnectTimeout(5000).setSocketTimeout(5000).build();
        httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).setConnectionManager(poolConnectionManager).build();
    }

    /**
     * get
     *
     * @param url 请求路径
     * @return
     * @throws IOException
     */
    public static String get(String url) throws IOException {
        if (StringUtils.isBlank(url)) return null;
        //设置请求参数
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        return parse(response);
    }


    /**
     * post json
     *
     * @param json 请求json body
     * @param url  请求路径
     * @return
     */
    public static String postJson(String json, String url) throws IOException {
        if (StringUtils.isBlank(json) || StringUtils.isBlank(url)) return null;
        HttpPost httpPost = new HttpPost(url);
        StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        return parse(response);
    }

    /**
     * post json
     *
     * @param json  json的请求参数
     * @param heads 请求头
     * @param url   请求路径
     * @return
     * @throws IOException
     */
    public static String postJson(String json, Map<String, String> heads, String url) throws IOException {
        if (StringUtils.isBlank(json) || StringUtils.isBlank(url)) return null;
        logger.info("url:{},json:{}", url, json);
        //设置json
        HttpPost httpPost = new HttpPost(url);
        StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
        httpPost.setEntity(entity);
        //设置请求头部
        if (heads != null && !heads.isEmpty()) {
            Set<String> headKeys = heads.keySet();
            for (String key : headKeys) {
                String value = heads.get(key);
                httpPost.addHeader(key, value);
            }
        }
        CloseableHttpResponse response = httpClient.execute(httpPost);
        String responseString = parse(response);
        logger.info("response:{}", responseString);
        return responseString;
    }


    /**
     * 解析结果集
     *
     * @param response
     * @return
     * @throws IOException
     */
    protected static String parse(CloseableHttpResponse response) throws IOException {
        String result = null;
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            result = "";
            if (statusCode != 200) {
                return result;
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, "utf-8");
                EntityUtils.consume(entity);
            }
        } catch (Exception e) {
            logger.error("parse error{}", ExceptionUtils.getStackFrames(e));
        } finally {
            response.close();
        }
        return result;
    }

    /**
     * 获取对应的文件流
     *
     * @param url
     * @return
     */
    public static InputStream download(String url) {
        if (StringUtils.isBlank(url)) return null;
        //设置请求参数
        HttpGet httpGet = new HttpGet(url);
        InputStream inputStream = null;
        try {
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            inputStream = entity.getContent();
        } catch (IOException e) {
            logger.info("download error:{}", ExceptionUtils.getStackFrames(e));
        }
        return inputStream;
    }


    public static void main(String[] args) {

    }
}
